import React, {useState,useEffect} from "react";
import {get, trim} from "lodash";
import {Modal, Form,Select, Input, Checkbox, Button, Col} from "antd/lib";
import { wrap as wrapDialog, DialogPropType } from "@/components/DialogWrapper";
import DynamicComponent from "@/components/DynamicComponent";
import {policy} from "@/services/policy";
import {UserProfile} from "@/components/proptypes";
import notification from "@/services/notification";
import {currentUser} from "@/services/auth";
import Templates from "@/services/templates";
import {StarOutlined, UploadOutlined} from "@ant-design/icons";
import Uploads from "@/services/uploads";
import Attaches from "@/services/attaches";
import Upload from "antd/lib/upload";
import ContractApply from "@/services/contractapply";
import moment from "moment";
import {useOrgunit} from "@/services/customer";
function CreateTemplatesDialog({ templates, dialog }) {
  //const {optionsLoaded, options } = useQueryEnumsItems('contract_enum');
  const [dataLoaded, setDataLoaded] = useState(templates.id ===0 ? true : false);
  const [id, setid] = useState(templates.id);
  const [code, setCode] = useState("");
  const [name, setName] = useState("");
  const [orgunit_id, setorgunit_id] = useState(currentUser.orgunit_id);
  const {optionsLoaded, options } = useOrgunit('orgunit');
  const [type, settype] = useState("");
  const [typename, settypename] = useState("");
  const [is_active, setis_active] = useState(false);
  const [template, settemplate] = useState("");
  const [attachesid, setattachesid] = useState(0);
  const [attachessel, setattachessel] = useState(true);
  const [annex, setannex] = useState([]);
  const [isValid, setIsValid] = useState(false);
  const [saveInProgress, setSaveInProgress] = useState(false);
  const isCreateTemplatesEnabled = useState(true);//policy.isAdmin() || policy.isDefault();
  const [views, setviews] = useState(false);
  useEffect(() => {
    settype(templates.type);
    settypename(templates.typename);
    if(id===0){
      Templates.getid({id: 0}).then(data => {
           setid(data[0].id);
        })
        .catch(error => {
        });
    }
    if (templates.id === 0){
      let item = {
        tblname: "templates",
        bill_date: moment(),
        type: 0,
        tblfield: "code",
      }
      ContractApply.getcode(item).then(data => {
        setCode(data[0].code);
        setDataLoaded(true);
      })
        .catch(error => {
          setDataLoaded(true);
        });
  }else{
        setCode(templates.code);
        setName(templates.name);
        setorgunit_id(templates.orgunit_id);
        settemplate(templates.template);
        setis_active(templates.is_active);
        setviews(templates.views);
        if(templates.views){
          setSaveInProgress(true);
        }
        // settype(templates.type);
        // settypename(templates.typename);
        setDataLoaded(true);
    if(attachessel){
      Attaches.get({sourceid:templates.id,type:"templates" }).then(data => {
          setattachesid(data.id);
          setannex(data.annex);
      }).catch(error => {
          // setattachesid(0);
          // setannex([]);
      });
      setattachessel(false);
    }
  }
  }, [templates]);
  useEffect(() => {
    if(views){
      document.getElementById("goods_template_detailsel").innerHTML = template;
    }
  }, [template]);
  function handleCodeChange(event) {
    const value = trim(event.target.value);
    setCode(value);
    setIsValid(value !== "" && name !== "");
  }

  function handleTemplateChange(event) {
    const value = trim(event.target.value);
    settemplate(value);
    setIsValid(name !== "" && code !== "" );
  }
  function handleis_activeChange(event) {
    const value = event.target.checked;
    setis_active(value);
    setIsValid(name !== "" && code !== "" );
  }
  function handleNameChange(event) {
    const value = trim(event.target.value);
    setName(value);
    setIsValid(value !== "" && code !== "" );
  }
  function handleOrgunitChange(event) {
    const value = event;
    setorgunit_id(value);
    setIsValid(name !== "" && code !== "" );
  }
  function handleSubmit() {
    setSaveInProgress(true);
    if(templates.id===1){
      notification.error("空白模板不能修改");
      return ;
    }
   let data={id: id,//
            userid: currentUser.id,//--操作员ID
            code: code,
            name: name,
            type: type,
            orgunit_id: orgunit_id,
            annex: annex,
            attachesid: attachesid,
            is_active: is_active,
            template: template }
    if(templates.id===0) {
      Templates.create(data)
        .then(() => {
          dialog.close({ success: true});
        })
        .catch(error => {
          notification.error(error.message, error.detailedMessage);
          setSaveInProgress(false);
        });
    }else{
      Templates.save(data)
        .then(() => {
          dialog.close({ success: true});
        })
        .catch(error => {
          notification.error(error.message, error.detailedMessage);
          setSaveInProgress(false);
        });
    }
  }

 function  handledown(file){
     let  filename=file.url;
     let names=file.name;
     if(names.split('.')[1]!==filename.split('.')[1]){
      filename=filename.split('.')[0] +'.'+names.split('.')[1];
     }
     let AjaxUrl = 'api/upload/downloadfile';
     fetch(AjaxUrl ,{
      method: 'POST',
      body: window.JSON.stringify({filename: filename}),
      credentials: 'include',
      headers: new Headers({
        'Content-Type': 'application/json'
      })}).then((response) => {
      response.blob().then(blob => {
        const aLink = document.createElement('a');
        document.body.appendChild(aLink);
        aLink.style.display='none';
        const objectUrl = window.URL.createObjectURL(blob);
        aLink.href = objectUrl;
        aLink.download = file.name;
        aLink.click();
        document.body.removeChild(aLink);
      });
    }).catch((error) => {
      console.log(error);
    });
  };
  function handleChange(info) {
    let fileList = [...info.fileList];
    var newd=[];
    fileList.forEach(file => {
          if (file.response) {
            // Component will show file.url as link
            file.url = 'static/file/'+file.response.filename;
          }
     // if(file.status==="done") {
         const b=[{
                  uid: file.uid,
                  name: file.name,
                  status: file.status,
                  url: file.url
          }];
        if (newd.length < 1) {
          newd = b;
        } else {
          newd.push.apply(newd, b);
        }
     // }
        });
    setannex(newd);
 };
 function annexlist(){
   if(annex.length>0){
    return (
      annex.map(item => (
        <li key={item.uid}>{item.name +" url: /static/file/"  + item.url}</li>
      ))
    );
  }else{
    return <li key="1">空</li>
  }
 }
 function  getPdfURL(){
        const _this = this;
        const props = {
            name: 'file',
            action: 'api/upload/uploadfile/templates/editor/0/0/'+_this.props.id,
            headers: {
                authorization: 'authorization-text',
            },
         onChange: handleChange,
         // onChange(info) {
         //        let fileList = [...info.fileList];
         //    var newd=[];
         //    fileList.forEach(file => {
         //          if (file.response) {
         //            file.url = file.response.filename;
         //          }
         //         const b=[{
         //                  uid: file.uid,
         //                  name: file.name,
         //                  status: file.status,
         //                  url: file.url
         //          }];
         //        if (newd.length < 1) {
         //          newd = b;
         //        } else {
         //          newd.push.apply(newd, b);
         //        }
         //        });
         //        _this.setannex(newd);
         //      },
           onDownload: handledown,
           onRemove(infos){
            let uid=infos.uid;
            const id=_this.props.id;
            Uploads.removefile({sourcetype: "templates",sourceid:id,uid:uid}).then(data => {
                 if(data.code==="sucess"){
                    notification.success(data.msg);
                 }
                 else{
                  notification.error(data.msg);
                  }
                }).catch(error => {
                  notification.error(get(error, "response.data.message", "删除失败."));
                });
           },
            showUploadList: {
            showDownloadIcon: true,
            downloadIcon: '下载',
            showRemoveIcon: true,
            removeIcon: <StarOutlined onClick={e => console.log(e, 'custom removeIcon event')} />,
          },
        };
        return props;
    };
  return (
    <Modal
      {...dialog.props}
      {...(isCreateTemplatesEnabled ? {} : { footer: null })}
      title="模板管理"
      width={document.querySelector('body').offsetWidth*0.6}
      okText="保存"
      cancelText="取消"
      okButtonProps={{
        disabled: !isValid || saveInProgress,
        loading: saveInProgress,
        "data-test": "DashboardSaveButton",
      }}
      // cancelButtonProps={{
      //   disabled: saveInProgress,
      // }}
      onOk={handleSubmit}
     // closable={!saveInProgress}
      maskClosable={!saveInProgress}
      wrapProps={{
        "data-test": "CreateDashboardDialog",
      }}>
      {/* {dataLoaded && ( */}
      <DynamicComponent name="CreateTemplatesDialogExtra" disabled={!isCreateTemplatesEnabled}>
      <Form layout="horizontal" {...{labelCol: { span: 4 }, wrapperCol: { span: 14 },} }>
        <Form.Item style={{ marginBottom: 5 }} label="模板编码">
        <Input
          value={code}
          onChange={handleCodeChange}
          placeholder="模板编码"
          disabled={saveInProgress}
          autoFocus
        />
        </Form.Item>
        <Form.Item style={{ marginBottom: 5 }} label="模板名称">
        <Input
          value={name}
          onChange={handleNameChange}
          placeholder="模板名称"
          disabled={saveInProgress}
        />
        </Form.Item>
        {optionsLoaded && (
        <Form.Item style={{ marginBottom: 5 }} label="部门">
              <Select style={{ width:  300 }}
                    showSearch
                    optionFilterProp="children"
                      value={orgunit_id}
                      onChange={handleOrgunitChange}  
                      disabled={saveInProgress}
                 >
              {(options || []).map(item => (
                <Select.Option key={item.id} value={item.id}>{item.name}</Select.Option>
              ))}
              </Select>
        </Form.Item>
        )}
        {/* <Form.Item style={{ marginBottom: 5 }} label="合同类别">
        <Input
          value={typename}
          disabled={true}
        /> */}
        <Form.Item style={{ marginBottom: 5 }} label="附件">
        {annexlist()}
          {/*<p> {annex} </p>*/}
          {/*{annex.forEach(file => {if(file.status==="done") { <p> file.name </p>}})}*/}
            <Upload {...getPdfURL()} fileList={annex}>
              <Button>
                <UploadOutlined /> 上传
              </Button>
            </Upload>
        {/* </Form.Item> */}
        </Form.Item>
        {!views && ( <Form.Item style={{ marginBottom: 5 }} label="模板">
              <p>模板用HTML标签语法，如果需要输入的标签,要设置：class="contracttemplate"，并且ID不能重复.
                如果模板中需要用到附件，先上传，会显示路径，如上传一个PDF文件：生产部署.pdf url: /static/file/20200801/e160424dd3a111eaba9d000c29e34bd9.pdf
                在模板中设置："iframe csp="script-src 'unsafe-inline'" src="/static/images/8f1d338fd1ab11eab884000c29e34bd9.pdf" width="800" height="600"/iframe"
                如果是图片："img src="/static/images/footlogo.jpg""
              </p>
              <textarea
                rows="15" 
                cols={document.querySelector('body').offsetWidth*0.6/12}
                textAlignVertical="top"
                height="100px"
                value={template}
                onChange={handleTemplateChange}
                placeholder="模板"
                disabled={saveInProgress}
              />
						</Form.Item> )}
          {views && (<Form.Item style={{ marginBottom: 7 }} label="模板预览">
            <div id="goods_template_detailsel"/>
						</Form.Item>)}
        <Form.Item style={{ marginBottom: 5 }} label="停用">
        <Checkbox
          checked ={is_active}
          onChange={handleis_activeChange}
          disabled={saveInProgress}
          autoFocus
        />
        </Form.Item>
      </Form>
      </DynamicComponent>
       {/* )} */}
    </Modal>
  );
}

CreateTemplatesDialog.propTypes = {
  Templates: UserProfile.isRequired,
  dialog: DialogPropType.isRequired,
};

export default wrapDialog(CreateTemplatesDialog);
